#include "aprs3.h"
#include "sigs3.h"
#include "utils.h"

static void 
closed_connection(serf_connection_t *conn, 
                  void *closed_baton,
                  apr_status_t why, 
                  apr_pool_t *pool)
{
    if (why) {
        abort();
    }
}

static serf_bucket_t* 
conn_setup(apr_socket_t *skt, 
           void *setup_baton,
           apr_pool_t *pool)
{
    serf_bucket_t *c;
    s3_connection_t *conn = setup_baton;

    c = serf_bucket_socket_create(skt, conn->bkt_alloc);
    if (conn->ctx->using_ssl) {
        c = serf_bucket_ssl_decrypt_create(c, conn->ssl_ctx, conn->bkt_alloc);
        if (!conn->ssl_ctx) {
            conn->ssl_ctx = serf_bucket_ssl_decrypt_context_get(c);
        }
    }

    return c;
}

static serf_bucket_t* 
accept_response(serf_request_t *request,
                serf_bucket_t *stream,
                void *acceptor_baton,
                apr_pool_t *pool)
{
    serf_bucket_t *c;
    serf_bucket_alloc_t *bkt_alloc;

    /* get the per-request bucket allocator */
    bkt_alloc = serf_request_get_alloc(request);

    /* Create a barrier so the response doesn't eat us! */
    c = serf_bucket_barrier_create(stream, bkt_alloc);

    return serf_bucket_response_create(c, bkt_alloc);
}

static apr_status_t 
handle_response(serf_request_t *request,
                serf_bucket_t *response,
                void *handler_baton,
                apr_pool_t *pool)
{
    const char *data;
    apr_size_t len;
    serf_status_line sl;
    apr_status_t status, rv;
    s3_request_t *req = handler_baton;

    status = serf_bucket_response_status(response, &sl);
    if (status) {
        if (APR_STATUS_IS_EAGAIN(status)) {
            return status;
        }
        abort();
    }

    while (1) {

        /* Set Error Code */
        if (sl.code == 200 || sl.code == 204) {
            req->err = S3_SUCCESS;
        }
        else {
            req->err = S3_ERROR;
        }

        /* Read Response */
        status = serf_bucket_read(response, 2048, &data, &len);
        if (SERF_BUCKET_READ_ERROR(status))
            return status;

        /* are we done yet? */
        if (APR_STATUS_IS_EOF(status)) {
            apr_atomic_dec32(&req->acceptor_baton->ctx->requests_outstanding);
            return APR_EOF;
        }

        /* have we drained the response so far? */
        if (APR_STATUS_IS_EAGAIN(status))
            return status;

        switch (req->type) {
            case S3_CREATE_BUCKET:
                break;
            case S3_LIST_FILES:
            case S3_LIST_BUCKETS:
                /* XML Response */
                if (!req->xc) {
                    req->xc = xmlCreatePushParserCtxt(NULL, 
                                                      NULL, 
                                                      (const char*)data, 
                                                      len,
                                                      "");
                    if (req->xc) {
                        req->xc->replaceEntities = 1;
                        req->xc->loadsubset = 1;
                    }
                }
                else {
                    xmlParseChunk(req->xc, (const char*)data, len, 0);
                }

                /* TODO add verbose */
                 
                /*
                 fwrite(data, 1, len, stderr);
                 */
                
                break;
            case S3_GET:
                /* setup the output file */
                if (!req->outfile) {
                    if ((rv = apr_file_open(&req->outfile, 
                                            req->s3_data->output_filename,
                                            APR_WRITE | APR_CREATE | APR_BINARY,
                                            APR_OS_DEFAULT,
                                            req->subpool)) != APR_SUCCESS ) {
                        req->outfile = NULL;
                        fprintf(stderr, "Could not open output file %s\n",
                                req->s3_data->output_filename);
                        return rv;
                    }
                }

                /* write the data out */
                rv = apr_file_write_full(req->outfile, data, len, NULL);
                if (rv != APR_SUCCESS) {
                    char err_buf[100];
                    fprintf(stderr, "apr_file_write_full: %s\n", 
                            apr_strerror(rv, err_buf, sizeof(err_buf)));
                    return rv;
                }

                break;

            default:
                /* got some data. print it out. */
                fwrite(data, 1, len, stderr);
                break;
        }

        /* loop to read some more. */
    }
    /* NOTREACHED */
}

static apr_status_t 
setup_request(serf_request_t *request,
              void *setup_baton,
              serf_bucket_t **req_bkt,
              serf_response_acceptor_t *acceptor,
              void **acceptor_baton,
              serf_response_handler_t *handler,
              void **handler_baton,
              apr_pool_t *pool)
{
    s3_request_t *ctx = setup_baton;
    serf_bucket_t *hdrs_bkt;
    serf_bucket_t *body_bkt;
    char *rfcdate;
    apr_off_t fsize = 0;
    
    rfcdate = apr_palloc(pool, APR_RFC822_DATE_LEN);
    apr_rfc822_date(rfcdate, ctx->req_time); 

    if (ctx->req_body_path) {
        apr_file_t *file;
        apr_finfo_t finfo;
        apr_status_t status;

        status = apr_file_open(&file, ctx->req_body_path, APR_READ,
                               APR_OS_DEFAULT, pool);

        if (status) {
            printf("Error opening file (%s)\n", ctx->req_body_path);
            return status;
        }

        status = apr_file_info_get(&finfo, APR_FINFO_SIZE, file);
        if (status) {
            printf("Error fetching file size (%s)\n", ctx->req_body_path);
            return status;
        }

        body_bkt = serf_bucket_file_create(file,
                                           serf_request_get_alloc(request));

        fsize = finfo.size;

    }
    else {
        body_bkt = NULL;
    }

    *req_bkt = serf_bucket_request_create(ctx->method, 
                                          ctx->path, 
                                          body_bkt,
                                          serf_request_get_alloc(request));

    hdrs_bkt = serf_bucket_request_get_headers(*req_bkt);
    serf_bucket_headers_setn(hdrs_bkt, "Host", S3_HOST_NAME);
    serf_bucket_headers_setn(hdrs_bkt, "Date", rfcdate);

    //serf_bucket_headers_setn(hdrs_bkt, "User-Agent", "aprs3/" SERF_VERSION_STRING);
    
    if (ctx->req_body_path && fsize > 0) {
        serf_bucket_headers_setn(hdrs_bkt, "Content-Type", "text/txt");
        serf_bucket_headers_setn(hdrs_bkt, "Content-Length", 
                                 apr_psprintf(pool, "%u", fsize));
    }

    serf_bucket_headers_setn(hdrs_bkt, "Authorization", 
                             s3_generate_signature(ctx, hdrs_bkt, pool));

    apr_atomic_inc32(&(ctx->acceptor_baton->ctx->requests_outstanding));

    if (ctx->acceptor_baton->ctx->using_ssl) {
        serf_bucket_alloc_t *req_alloc;
        s3_connection_t *conn_ctx = ctx->acceptor_baton;

        req_alloc = serf_request_get_alloc(request);

        if (conn_ctx->ssl_ctx == NULL) {
            *req_bkt =
                serf_bucket_ssl_encrypt_create(*req_bkt, NULL,
                                               conn_ctx->bkt_alloc);
            conn_ctx->ssl_ctx =
                serf_bucket_ssl_encrypt_context_get(*req_bkt);
        }
        else {
            *req_bkt =
                serf_bucket_ssl_encrypt_create(*req_bkt, conn_ctx->ssl_ctx,
                                               conn_ctx->bkt_alloc);
        }
    }

    *acceptor = ctx->acceptor;
    *acceptor_baton = ctx->acceptor_baton;
    *handler = ctx->handler;
    *handler_baton = ctx;

    return APR_SUCCESS;
}

s3_connection_t*
s3_connection_create(s3_context_t *ctx, apr_pool_t *pool)
{
    apr_status_t status;
    s3_connection_t *conn = apr_palloc(pool, sizeof(*conn));

    status = apr_sockaddr_info_get(&conn->address,
                                   S3_HOST_NAME, 
                                   APR_UNSPEC, 
                                   ctx->using_ssl?S3_HTTPS_PORT:S3_HTTP_PORT, 
                                   0,
                                   pool);

    if (status) {
        printf("Error creating address: %d\n", status);
        exit(1);
    }

    conn->bkt_alloc = serf_bucket_allocator_create(pool, NULL, NULL);
    conn->ssl_ctx   = NULL;
    conn->ctx   = ctx;
    conn->serf_conn = serf_connection_create(ctx->serf_ctx, 
                                             conn->address,
                                             conn_setup, conn,
                                             closed_connection, conn,
                                             pool);

    return conn;
}

s3_context_t* 
s3_context_create(const char *key, 
                  const char *id, 
                  int using_ssl, 
                  apr_pool_t *pool)
{
    s3_context_t *ctx = apr_palloc(pool, sizeof(*ctx));
    ctx->s3_key = apr_pstrdup(pool, key);
    ctx->s3_id  = apr_pstrdup(pool, id);
    ctx->using_ssl = using_ssl;
    ctx->requests_outstanding = 0;
    ctx->serf_ctx = serf_context_create(pool);
    return ctx;
}

void 
s3_connection_close(s3_connection_t *conn)
{
    if (!conn || !conn->serf_conn) {
        return;
    }
    serf_connection_close(conn->serf_conn);
}

apr_status_t 
s3_run(s3_context_t *ctx, apr_pool_t *pool)
{
    apr_status_t rv;

    while (1) {
        rv = serf_context_run(ctx->serf_ctx, SERF_DURATION_FOREVER, pool);
        if (APR_STATUS_IS_TIMEUP(rv))
            continue;
        if (rv) {
            char buf[200];

            printf("Error running context: (%d) %s\n", rv,
                   apr_strerror(rv, buf, sizeof(buf)));
            exit(1);
        }
        if (!apr_atomic_read32(&ctx->requests_outstanding)) {
            break;
        }
    }

    return rv;
}

void 
s3_request_create_list_bucket(s3_request_t *req, 
                              s3_data_t *s3_data, 
                              apr_pool_t *pool)
{
    req->path = "/";
    req->method = "GET";
    req->req_body_path = NULL;
    req->s3_data = s3_data;
}

void 
s3_request_create_list_files(s3_request_t *req, 
                             s3_data_t *s3_data, 
                             apr_pool_t *pool)
{
    req->path = apr_pstrcat(pool, "/", s3_data->bucket, NULL);
    req->method = "GET";
    req->req_body_path = NULL;
    req->s3_data = s3_data;
}

void 
s3_request_create_bucket(s3_request_t *req, 
                             s3_data_t *s3_data, 
                             apr_pool_t *pool)
{
    req->path = apr_pstrcat(pool, "/", s3_data->bucket, NULL);
    req->method = "PUT";
    req->req_body_path = NULL;
    req->s3_data = s3_data;
}

void 
s3_request_delete_bucket(s3_request_t *req, 
                         s3_data_t *s3_data, 
                         apr_pool_t *pool)
{
    req->path = apr_pstrcat(pool, "/", s3_data->bucket, NULL);
    req->method = "DELETE";
    req->req_body_path = NULL;
    req->s3_data = s3_data;
}

void 
s3_request_get(s3_request_t *req, 
               s3_data_t *s3_data, 
               apr_pool_t *pool)
{
    req->path = apr_pstrcat(pool, 
                            "/", s3_data->bucket, 
                            "/", s3_data->objkey,
                            NULL);

    req->method = "GET";
    req->req_body_path = NULL;
    req->s3_data = s3_data;
}

void 
s3_request_delete_object(s3_request_t *req, 
                         s3_data_t *s3_data, 
                         apr_pool_t *pool)
{
    req->path = apr_pstrcat(pool, 
                            "/", s3_data->bucket, 
                            "/", s3_escape_url(s3_data->objkey, pool),
                            NULL);

    req->method = "DELETE";
    req->req_body_path = NULL;
    req->s3_data = s3_data;
}

void 
s3_request_put(s3_request_t *req, 
               s3_data_t *s3_data, 
               apr_pool_t *pool)
{
    req->path = apr_pstrcat(pool, 
                            "/", s3_data->bucket, 
                            "/", s3_escape_url(s3_data->objkey, pool),
                            NULL);

    req->method = "PUT";
    req->req_body_path = apr_pstrdup(pool, s3_data->objkey);
    req->s3_data = s3_data;
}

s3_request_t* 
s3_create_request(s3_connection_t *conn, 
                  s3_request_e type, 
                  s3_data_t *s3_data, 
                  apr_pool_t *pool)
{
    s3_request_t *req = apr_pcalloc(pool, sizeof(*req));
    char *rfcdate = apr_palloc(pool, APR_RFC822_DATE_LEN);
    char *authdata;

    req->type = type;
    req->req_time = apr_time_now();
    req->acceptor_baton = conn;
    req->outfile = NULL;
    apr_pool_create(&req->subpool, pool);

    switch (type) {
        case S3_LIST_FILES:
            s3_request_create_list_files(req, s3_data, pool);
            break;
        case S3_LIST_BUCKETS:
            s3_request_create_list_bucket(req, s3_data, pool);
            break;
        case S3_CREATE_BUCKET:
            s3_request_create_bucket(req, s3_data, pool);
            break;
        case S3_DELETE_BUCKET:
            s3_request_delete_bucket(req, s3_data, pool);
            break;
        case S3_PUT:
            s3_request_put(req, s3_data, pool);
            break;
        case S3_GET:
            s3_request_get(req, s3_data, pool);
            break;
        case S3_DELETE_OBJECT:
            s3_request_delete_object(req, s3_data, pool);
            break;
        default:
            return NULL;
    }

    req->acceptor = accept_response;
    req->handler  = handle_response;
    req->serf_request = serf_connection_request_create(conn->serf_conn, 
                                                       setup_request,
                                                       req);
    return req;
}
